package com.javalearn;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class Counter {
	private AtomicInteger atomicI = new AtomicInteger(0);
	private volatile int i=0;
	private void unsafecount() {
		i++;
	}
	private void safeCount() {
		for(;;) {
			int i = atomicI.get();
			boolean suc = atomicI.compareAndSet(i, ++i);
			if(suc) {
				break;
			}else {
				System.out.println("false....old value:"+i+"new value:"+atomicI.get());
			}
		}
	}
	public static void main(String[] args) {
		final Counter cas = new Counter();
		List<Thread> ts = new ArrayList<Thread>(600);
		for(int i=0;i<100;i++) {	
			Thread t = new Thread(new Runnable() {
				public void run() {
					for(int i=0;i<10000;i++) {
						cas.unsafecount();
						cas.safeCount();
					}
				}
			});
			ts.add(t);
		}
		for(Thread t : ts) {
			t.start();
		}
		for(Thread t : ts) {
			try {
				t.join();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println("unsafe result:"+cas.i);
		System.out.println("safe result:"+cas.atomicI.get());
	}
}
